package com.xyz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xyz.entity.pojo.EquipmentTree;
import com.xyz.entity.vo.EquipmentTreeVO;
import com.xyz.service.EquipmentTreeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author yang DongYong
 * @Date 2025/3/3 - 03 - 03 - 15:46
 * @Description: com.xyz.service.impl
 * @version: 1.0
 */
@Service
public class EquipmentTreeServiceImpl implements EquipmentTreeService {

    @Override
    public List<String> reverseSelectNode(List<EquipmentTree> tree, Long currentNodeId) {
        List<EquipmentTreeVO> equipmentTreeVO = BeanUtil.copyToList(tree, EquipmentTreeVO.class);
        List<String> nodeStrList = new ArrayList<>();
        printPathToRoot(equipmentTreeVO, currentNodeId, nodeStrList);
        Collections.reverse(nodeStrList);
        return nodeStrList;
    }


    private static void printPathToRoot(List<EquipmentTreeVO> node, Long currentNodeId, List<String> nodeStr) {
        // 基本结束条件：如果节点为空或者没有父节点
        if (node == null) {
            return;
        }
        node.forEach(item -> {
            if (currentNodeId.equals(item.getId())) {
                nodeStr.add(item.getName());
                printPathToRoot(node, item.getBaseId(), nodeStr);
            }
        });
    }

    public static void main(String[] args) {
        // 构建一个简单的树结构
        List<EquipmentTreeVO> nodes = new ArrayList<>();

        EquipmentTreeVO root = new EquipmentTreeVO();
        root.setId(1L);
        root.setName("根节点");
        root.setBaseId(0L);
        EquipmentTreeVO child1 = new EquipmentTreeVO();
        child1.setId(2L);
        child1.setName("子节点1");
        child1.setBaseId(1L);
        EquipmentTreeVO grandChild = new EquipmentTreeVO();
        grandChild.setId(3L);
        grandChild.setName("孙子节点");
        grandChild.setBaseId(2L);
        // 将节点添加到列表中
        nodes.add(root);
        nodes.add(child1);
        nodes.add(grandChild);

        // 创建一个用于存储路径的列表
        List<String> nodeStr = new ArrayList<>();

        // 从孙子节点开始向上找到根节点
        printPathToRoot(nodes, grandChild.getId(), nodeStr);

        // 输出路径
        System.out.println("从孙子节点到根节点的路径:");
        for (String name : nodeStr) {
            System.out.println(name);
        }
        Collections.reverse(nodeStr);
        String join = String.join("/", nodeStr);
        System.out.println(join);
    }

}
